package site.jjqzplucky.user.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import site.jjqzplucky.user.domain.dto.UserDto;
import site.jjqzplucky.user.domain.form.UserForm;
import site.jjqzplucky.user.domain.po.User;
import site.jjqzplucky.user.mapper.UserMapper;
import site.jjqzplucky.user.service.UserService;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {

    @Override
    public String login(UserForm form) throws Exception {
        String password = this.hexPassword(form.getUsername(), form.getPassword());
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>().eq(User::getUsername, form.getUsername()).eq(User::getPassword, password);
        User user = this.getOne(wrapper);
        if(user == null){
            throw new Exception();
        }
        StpUtil.login(user.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return tokenInfo.tokenValue;
    }

    @Override
    public User curUser() {
        Long id = Long.valueOf((String) StpUtil.getLoginId());
        return this.getById(id);
    }

    @Override
    public void create(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        String password = this.hexPassword(userDto.getUsername(), userDto.getPassword());
        user.setPassword(password);
        this.save(user);
    }

    private String hexPassword(String salt, String password){
        MD5 md5 = MD5.create();
        //前六位字符
        String tempStart = StrUtil.subWithLength(salt, 0, 6);
        //后三位
        String tempEnd = StrUtil.subSuf(salt, salt.length() - 3);
        //混淆原始密码加密
        return md5.digestHex(tempStart + password + tempEnd);
    }
}
